package com.xuecheng.base.expection;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.ArrayList;

/**
 * @Author: Ren(任佳宝)
 * @Description: GlobalExceptionHandler
 * @Date: 2024/8/21 下午8:26
 * @Version: 1.0
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 处理自己的异常
     *
     * @param e 异常信息
     * @return 返回给前端的异常信息
     */
    @ExceptionHandler(XueChengPlusException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public RestErrorResponse ex(XueChengPlusException e) {

        log.error("系统异常{}", e.getErrMessage());
        return new RestErrorResponse(e.getErrMessage());
    }


    /**
     * 处理字段验证异常
     *
     * @param e 异常信息
     * @return 返回给前端的异常信息
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public RestErrorResponse ex(MethodArgumentNotValidException e) {

        BindingResult bindingResult = e.getBindingResult();
        // 存放错误信息
        ArrayList<String> errorsList = new ArrayList<>();
        bindingResult.getFieldErrors().stream().forEach(item -> {
            errorsList.add(item.getDefaultMessage());
        });
        // 将错误信息拼接到一起
        String errorsStr = StringUtils.join(errorsList, ",");
        log.error("系统异常{}", errorsStr);
        return new RestErrorResponse(errorsStr);
    }

    /**
     * 处理系统异常
     *
     * @param e 异常信息
     * @return 返回给前端的异常信息
     */
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public RestErrorResponse ex(Exception e) {

        log.error("系统异常{}", e.getMessage());
        return new RestErrorResponse(CommonError.UNKOWN_ERROR.getErrMessage());
    }
}
